package com.xk.school_device.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xk.school_device.common.PageEntity;
import com.xk.school_device.common.Result;
import com.xk.school_device.entity.Maintenances;
import com.xk.school_device.entity.req.MaintenancesReq;
import com.xk.school_device.service.IDevicesService;
import com.xk.school_device.service.IMaintenancesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xk
 * @since 2025-04-16
 */
@RestController
@RequestMapping("/api/maintenance")
public class MaintenancesController {

    @Autowired
    private IMaintenancesService maintenancesService;

    @Autowired
    private IDevicesService devicesService;
    @PostMapping("query")
    public Result getMaintenanceRecords(@RequestBody MaintenancesReq maintenancesReq) {
        return maintenancesService.getMaintenanceRecords(maintenancesReq.getPage(), maintenancesReq.getPageSize());
    }

    @PostMapping("/register")
    public Result register(@RequestBody Maintenances maintenances) {
        maintenances.setMaintenanceId(String.valueOf(UUID.randomUUID()));
        if (maintenances.getMaintenanceBy() == null || maintenances.getMaintenanceBy().isEmpty()){
            maintenances.setMaintenanceBy(StpUtil.getLoginIdAsString());
        }
        maintenances.setStatus(0);
        devicesService.updateMaintenanceId(maintenances.getDeviceId(),"under_maintenance");
        return maintenancesService.save(maintenances) ? Result.success("添加成功") : Result.failure("添加失败");
    }

    @PostMapping("/finish")
    public Result getFinish(@RequestBody MaintenancesReq maintenancesReq) {
        return maintenancesService.getMaintenanceFinishs(maintenancesReq.getPage(), maintenancesReq.getPageSize());
    }
    @PostMapping("/update")
    public Result update(@RequestBody Maintenances maintenances) {
        devicesService.updateMaintenanceId(maintenances.getDeviceId(),"in_stock");
        QueryWrapper<Maintenances> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("maintenance_id", maintenances.getMaintenanceId());
        Maintenances maintenances1 = maintenancesService.getOne(queryWrapper);
        maintenances1.setStatus(1);
        return maintenancesService.updateById(maintenances1) ? Result.success("确认成功") : Result.failure("确认失败");
    }

}
